// 云平台管理系统 - 主应用脚本
const DEFAULT_AVATAR = '/static/img/default-avatar.svg';
class CloudPlatformApp {
    constructor() {
        this.currentPage = 'home';
        this.profilePollingInterval = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadPage('home');
    }

    bindEvents() {
        // 用户菜单交互
        const userMenuBtn = document.getElementById('userMenuBtn');
        const userDropdown = document.getElementById('userDropdown');
        
        if (userMenuBtn && userDropdown) {
            // 鼠标悬停显示下拉菜单
            userMenuBtn.addEventListener('mouseenter', () => {
                userDropdown.classList.add('show');
            });
            
            // 鼠标离开按钮和下拉菜单时隐藏
            userMenuBtn.addEventListener('mouseleave', () => {
                setTimeout(() => {
                    if (!userDropdown.matches(':hover')) {
                        userDropdown.classList.remove('show');
                    }
                }, 100);
            });
            
            userDropdown.addEventListener('mouseenter', () => {
                userDropdown.classList.add('show');
            });
            
            userDropdown.addEventListener('mouseleave', () => {
                userDropdown.classList.remove('show');
            });
        }

        // 导航菜单点击事件
        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const page = link.getAttribute('data-page');
                this.switchPage(page);
            });
        });
        
        // 账号管理下拉菜单点击事件
        const userDropdownItems = document.querySelectorAll('.dropdown-item[data-page]');
        userDropdownItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const page = item.getAttribute('data-page');
                this.switchPage(page);
                // 隐藏下拉菜单
                const userDropdown = document.getElementById('userDropdown');
                if (userDropdown) {
                    userDropdown.classList.remove('show');
                }
            });
        });
    }

    switchPage(page) {
        // 权限拦截：普通用户禁止访问用户管理
        if (page === 'users' && !this.canManageUsers()) {
            CloudPlatform.showMessage('无权限访问用户管理', 'error');
            return;
        }
        // 更新导航菜单激活状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });
        const activeLink = document.querySelector(`[data-page="${page}"]`);
        if (activeLink) {
            activeLink.parentElement.classList.add('active');
        }
        this.loadPage(page);
    }

    async loadPage(page) {
        this.currentPage = page;
        const contentWrapper = document.getElementById('contentWrapper');
        
        if (!contentWrapper) return;
    
        // 清理上一个页面的轮询（例如profile）
        this.stopProfilePolling();
    
        // 显示加载动画
        contentWrapper.innerHTML = `
            <div class="loading">
                <div class="spinner"></div>
            </div>
        `;
    
        try {
            const content = await this.getPageContent(page);
            contentWrapper.innerHTML = content;
            if (page === 'profile') {
                this.initProfileFragment();
            }
            if (page === 'users') {
                this.initUsersPage();
            }
        } catch (error) {
            console.error('页面加载失败:', error);
            contentWrapper.innerHTML = this.getErrorPage();
        }
    }

    async getPageContent(page) {
        // 模拟API调用获取页面内容
        if (page === 'profile') {
            return await this.fetchProfileFragment();
        }
        // 其他页面保持原逻辑
        return new Promise((resolve) => {
            setTimeout(() => {
                const content = this.generatePageContent(page);
                resolve(content);
            }, 300);
        });
    }

    generatePageContent(page) {
        // 访问控制：非管理员不可访问用户管理
        if (page === 'users' && !this.canManageUsers()) {
            return this.getUnauthorizedPage();
        }
        const pageTemplates = {
            'home': this.getHomePage(),
            'ai-access': this.getAIAccessPage(),
            'visualization': this.getVisualizationPage(),
            'inspection': this.getInspectionPage(),
            'notifications': this.getNotificationsPage(),
            'users': this.getUsersPage(),
            'files': this.getFilesPage(),
            'profile': this.getProfilePage()
        };
        return pageTemplates[page] || this.getNotFoundPage();
    }

    getHomePage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">欢迎使用云平台管理系统</h1>
                    <p class="page-description">一站式云平台管理解决方案，助您高效管理各类资源和服务</p>
                </div>
                
                <div class="card-grid">
                    <div class="card">
                        <div class="card-header">
                            <div class="card-icon bg-grad-1">
                                <i class="fas fa-robot"></i>
                            </div>
                            <h3 class="card-title">AI接入</h3>
                        </div>
                        <div class="card-content">
                            <p>集成多种AI服务，提供智能化的数据处理和分析能力，助力业务智能化升级。</p>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <div class="card-icon bg-grad-2">
                                <i class="fas fa-chart-bar"></i>
                            </div>
                            <h3 class="card-title">可视化应用</h3>
                        </div>
                        <div class="card-content">
                            <p>提供丰富的数据可视化组件，支持实时数据展示和交互式分析，让数据更直观。</p>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <div class="card-icon bg-grad-3">
                                <i class="fas fa-search"></i>
                            </div>
                            <h3 class="card-title">巡检管理</h3>
                        </div>
                        <div class="card-content">
                            <p>自动化巡检系统，实时监控平台状态，及时发现并处理潜在问题。</p>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <div class="card-icon bg-grad-4">
                                <i class="fas fa-bell"></i>
                            </div>
                            <h3 class="card-title">订阅通知</h3>
                        </div>
                        <div class="card-content">
                            <p>灵活的消息订阅机制，支持多种通知方式，确保重要信息及时送达。</p>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <div class="card-icon bg-grad-5">
                                <i class="fas fa-users"></i>
                            </div>
                            <h3 class="card-title">用户管理</h3>
                        </div>
                        <div class="card-content">
                            <p>完善的用户权限管理体系，支持角色分配和权限控制，保障系统安全。</p>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <div class="card-icon bg-grad-6">
                                <i class="fas fa-folder"></i>
                            </div>
                            <h3 class="card-title">文件管理</h3>
                        </div>
                        <div class="card-content">
                            <p>统一的文件存储和管理系统，支持文件上传、下载、分享和版本控制。</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    getAIAccessPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">AI接入管理</h1>
                    <p class="page-description">管理和配置AI服务接入，支持多种AI模型和算法</p>
                </div>
                
                <div class="card">
                    <h3>AI服务列表</h3>
                    <p>这里将显示已接入的AI服务列表，包括服务状态、配置信息等。</p>
                    <div style="margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px;">
                        <p>功能开发中...</p>
                    </div>
                </div>
            </div>
        `;
    }

    getVisualizationPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">可视化应用</h1>
                    <p class="page-description">数据可视化展示和分析工具</p>
                </div>
                
                <div class="card">
                    <h3>数据仪表盘</h3>
                    <p>实时数据监控和可视化展示。</p>
                    <div style="margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px;">
                        <p>功能开发中...</p>
                    </div>
                </div>
            </div>
        `;
    }

    getInspectionPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">巡检管理</h1>
                    <p class="page-description">系统巡检和监控管理</p>
                </div>
                
                <div class="card">
                    <h3>巡检任务</h3>
                    <p>自动化巡检任务配置和执行。</p>
                    <div style="margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px;">
                        <p>功能开发中...</p>
                    </div>
                </div>
            </div>
        `;
    }

    getNotificationsPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">订阅通知</h1>
                    <p class="page-description">消息订阅和通知管理</p>
                </div>
                
                <div class="card">
                    <h3>通知设置</h3>
                    <p>配置消息订阅和通知方式。</p>
                    <div style="margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px;">
                        <p>功能开发中...</p>
                    </div>
                </div>
            </div>
        `;
    }

    getUsersPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">用户管理</h1>
                    <p class="page-description">用户账号和权限管理</p>
                </div>
                
                <div class="card">
                    <div class="toolbar">
                        <input id="users-search-input" type="text" placeholder="搜索用户名/邮箱/手机号" class="input flex-1 min-w-200">
                        <select id="users-role-filter" class="select">
                            <option value="">所有角色</option>
                            <option value="super_admin">超级管理员</option>
                            <option value="admin">管理员</option>
                            <option value="user">普通用户</option>
                        </select>
                        <button id="users-add-btn" class="btn btn-primary">
                            <i class="fas fa-plus"></i> 新增用户
                        </button>
                    </div>
                    <div class="table-wrapper">
                        <table class="table-basic">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>角色</th>
                                    <th>邮箱</th>
                                    <th>手机号</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="users-table-body"></tbody>
                        </table>
                    </div>
                    <div class="pagination-bar">
                        <div id="users-page-info" class="page-info">第 1 页</div>
                        <div>
                            <button id="users-prev-page" class="btn-page">上一页</button>
                            <button id="users-next-page" class="btn-page">下一页</button>
                        </div>
                    </div>
                </div>

                <div id="user-modal" class="modal-overlay hidden">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3 id="user-modal-title">添加用户</h3>
                            <button id="user-modal-close" class="modal-close">×</button>
                        </div>
                        <div class="modal-body">
                            <div class="modal-row">
                                <label>用户名</label>
                                <input id="form-username" type="text" class="input">
                            </div>
                            <div class="modal-row">
                                <label>角色</label>
                                <select id="form-role" class="select">
                                    <option value="user">普通用户</option>
                                    <option value="admin">管理员</option>
                                    <option value="super_admin">超级管理员</option>
                                </select>
                            </div>
                            <div class="modal-row">
                                <label>邮箱</label>
                                <input id="form-email" type="email" class="input">
                            </div>
                            <div class="modal-row">
                                <label>手机号</label>
                                <input id="form-phone" type="text" maxlength="11" class="input">
                            </div>
                            <div class="modal-row">
                                <label>状态</label>
                                <select id="form-active" class="select">
                                    <option value="true">启用</option>
                                    <option value="false">禁用</option>
                                </select>
                            </div>
                            <div class="modal-row">
                                <label>密码（新增时）</label>
                                <input id="form-password" type="password" class="input">
                            </div>
                            <div id="form-feedback" class="form-feedback"></div>
                        </div>
                        <div class="modal-footer">
                            <button id="user-modal-cancel" class="btn btn-outline">取消</button>
                            <button id="user-modal-save" class="btn btn-primary">保存</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    getFilesPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">文件管理</h1>
                    <p class="page-description">文件存储和管理系统</p>
                </div>
                
                <div class="card">
                    <h3>文件库</h3>
                    <p>文件上传、下载和管理功能。</p>
                    <div style="margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px;">
                        <p>功能开发中...</p>
                    </div>
                </div>
            </div>
        `;
    }

    getErrorPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">页面加载失败</h1>
                    <p class="page-description">抱歉，页面加载出现错误</p>
                </div>
                
                <div class="card">
                    <p>请检查网络连接或稍后重试。</p>
                </div>
            </div>
        `;
    }

    getUnauthorizedPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">无权限访问</h1>
                    <p class="page-description">您没有访问该模块的权限</p>
                </div>
                
                <div class="card">
                    <p>如需申请权限，请联系系统管理员。</p>
                </div>
            </div>
        `;
    }

    getProfilePage() {
        return `
            <div class="page-content">
                <div class="profile-container">
                    <div class="profile-header">
                        <div class="header-left">
                            <h2><i class="fas fa-user-cog"></i> 账号管理</h2>
                        </div>
                    </div>
                    
                    <div class="profile-tabs">
                        <div class="tab-buttons">
                            <button class="tab-btn active" data-tab="basic-info">基本资料</button>
                            <button class="tab-btn" data-tab="change-avatar">修改头像</button>
                            <button class="tab-btn" data-tab="password-manage">密码管理</button>
                            <button class="tab-btn" data-tab="register-account">注销账号</button>
                            <button class="tab-btn" data-tab="language">语言</button>
                        </div>
                    </div>
                    
                    <div class="profile-content">
                        <div class="tab-content active" id="basic-info">
                            <div class="user-info-card">
                                <div class="info-row">
                                    <div class="info-label">姓名</div>
                                    <div class="info-value">吴某某</div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">id</div>
                                    <div class="info-value">*******</div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">性别</div>
                                    <div class="info-value">
                                        <label class="radio-label">
                                            <input type="radio" name="gender" value="male" checked>
                                            <span>男</span>
                                        </label>
                                        <label class="radio-label">
                                            <input type="radio" name="gender" value="female">
                                            <span>女</span>
                                        </label>
                                    </div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">手机号</div>
                                    <div class="info-value">
                                        1*******5
                                        <button class="edit-btn">修改</button>
                                    </div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label">单位</div>
                                    <div class="info-value">
                                        <button class="add-unit-btn">+ 添加单位</button>
                                    </div>
                                </div>
                                
                                <div class="info-row">
                                    <div class="info-label"></div>
                                    <div class="info-value unit-display">泉州华光职业学院</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 其他标签页内容 -->
                    </div>
                </div>
            </div>
        `;
    }

    getNotFoundPage() {
        return `
            <div class="page-content">
                <div class="page-header">
                    <h1 class="page-title">页面不存在</h1>
                    <p class="page-description">您访问的页面不存在</p>
                </div>
                
                <div class="card">
                    <p>请检查页面地址是否正确。</p>
                </div>
            </div>
        `;
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', function() {
    new CloudPlatformApp();
});

// 全局工具函数
window.CloudPlatform = {
    // 显示消息提示
    showMessage: function(message, type = 'info') {
        // 这里可以添加消息提示的实现
        console.log(`[${type}] ${message}`);
    },
    
    // 格式化日期
    formatDate: function(date) {
        return new Date(date).toLocaleDateString('zh-CN');
    },
    
    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
};

CloudPlatformApp.prototype.fetchProfileFragment = async function() {
    try {
        const resp = await fetch('/profile/fragment/', { cache: 'no-store' });
        if (!resp.ok) throw new Error('加载片段失败');
        return await resp.text();
    } catch (e) {
        console.error('获取Profile片段失败:', e);
        return this.getErrorPage();
    }
};

CloudPlatformApp.prototype.initProfileFragment = function() {
    // 标签切换
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            tabBtns.forEach(b => b.classList.remove('active'));
            tabContents.forEach(c => c.classList.remove('active'));
            btn.classList.add('active');
            const tabId = btn.getAttribute('data-tab');
            document.getElementById(tabId)?.classList.add('active');
        });
    });

    // 基本资料编辑相关元素
    const usernameEl = document.getElementById('username-input');
    const phoneEl = document.getElementById('phone-input');
    const emailEl = document.getElementById('email-input');
    const usernameTextEl = document.getElementById('username-text');
    const phoneTextEl = document.getElementById('phone-text');
    const emailTextEl = document.getElementById('email-text');
    const editBtn = document.getElementById('edit-toggle-btn');
    // 新增：性别元素
    const genderTextEl = document.getElementById('gender-value');
    const genderGroup = document.getElementById('gender-input-group');
    const genderMaleEl = document.getElementById('gender-male');
    const genderFemaleEl = document.getElementById('gender-female');

    // 初始：隐藏输入、显示文本
    [usernameEl, phoneEl, emailEl].forEach(el => { if (el) { el.disabled = true; el.classList.add('hidden'); } });
    [usernameTextEl, phoneTextEl, emailTextEl].forEach(el => { if (el) el.classList.remove('hidden'); });
    // 新增：隐藏性别单选
    if (genderGroup) genderGroup.classList.add('hidden');
    [genderMaleEl, genderFemaleEl].forEach(el => { if (el) el.disabled = true; });

    // CSRF
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');

    const updateProfileUI = (data) => {
        const text = (v, fallback='未设置') => (v === null || v === undefined || v === '') ? fallback : v;
        const $ = (id) => document.getElementById(id);
        const setInput = (id, v) => { const el = $(id); if (el) el.value = (v === null || v === undefined) ? '' : v; };
        const setText = (id, v) => { const el = $(id); if (el) el.textContent = text(v); };
        setInput('username-input', data.username);
        setText('username-text', data.username);
        $('user-id-value') && ($('user-id-value').textContent = text(data.id));
        setInput('phone-input', data.phone);
        setText('phone-text', data.phone);
        setInput('email-input', data.email);
        setText('email-text', data.email);
        setText('role-name-value', data.role_name);
        const isActiveEl = $('is-active-value'); if (isActiveEl) isActiveEl.textContent = data.is_active ? '是' : '否';
        setText('date-joined-value', data.date_joined);
        setText('last-login-value', data.last_login);
        // 新增：同步性别文本与单选框
        const genderText = data.gender === 'male' ? '男' : (data.gender === 'female' ? '女' : '未设置');
        if (genderTextEl) genderTextEl.textContent = genderText;
        if (genderMaleEl) genderMaleEl.checked = (data.gender === 'male');
        if (genderFemaleEl) genderFemaleEl.checked = (data.gender === 'female');
        // 头像同步至 <i id="avatar-icon">
        const preview = document.querySelector('.avatar-preview');
        const iconEl = document.getElementById('avatar-icon');
        if (preview && iconEl && data.avatar_url !== undefined) {
            if (data.avatar_url) {
                iconEl.style.backgroundImage = `url('${data.avatar_url}')`;
                iconEl.classList.remove('fas', 'fa-user-circle');
                iconEl.style.fontSize = '';
            } else {
                iconEl.style.backgroundImage = `url('${DEFAULT_AVATAR}')`;
                iconEl.classList.add('fas', 'fa-user-circle');
            }
        }
    };

    // 编辑按钮切换
    if (editBtn) {
        editBtn.addEventListener('click', () => {
            const isEditing = editBtn.getAttribute('data-editing') === 'true';
            if (!isEditing) {
                [usernameEl, phoneEl, emailEl].forEach(el => { if (el) { el.disabled = false; el.classList.remove('hidden'); } });
                [usernameTextEl, phoneTextEl, emailTextEl].forEach(el => { if (el) el.classList.add('hidden'); });
                // 新增：显示性别单选，隐藏性别文本
                if (genderGroup) genderGroup.classList.remove('hidden');
                if (genderTextEl) genderTextEl.classList.add('hidden');
                [genderMaleEl, genderFemaleEl].forEach(el => { if (el) el.disabled = false; });
                editBtn.textContent = '保存';
                editBtn.setAttribute('data-editing', 'true');
            } else {
                // 保存逻辑
                const payload = {
                    username: usernameEl?.value || '',
                    phone: phoneEl?.value || '',
                    email: emailEl?.value || ''
                };
                // 新增：保存性别
                if (genderMaleEl?.checked) payload.gender = 'male';
                else if (genderFemaleEl?.checked) payload.gender = 'female';
                else payload.gender = '';
                fetch('/profile/update/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrftoken
                    },
                    body: JSON.stringify(payload)
                }).then(resp => resp.json()).then(json => {
                    if (json.status === 'success') {
                        updateProfileUI(json.data);
                        [usernameEl, phoneEl, emailEl].forEach(el => { if (el) { el.disabled = true; el.classList.add('hidden'); } });
                        [usernameTextEl, phoneTextEl, emailTextEl].forEach(el => { if (el) el.classList.remove('hidden'); });
                        // 新增：隐藏性别单选，显示性别文本，并禁用单选
                        if (genderGroup) genderGroup.classList.add('hidden');
                        if (genderTextEl) genderTextEl.classList.remove('hidden');
                        [genderMaleEl, genderFemaleEl].forEach(el => { if (el) el.disabled = true; });
                        editBtn.textContent = '编辑';
                        editBtn.setAttribute('data-editing', 'false');
                    } else {
                        alert(json.message || '保存失败');
                    }
                }).catch(() => alert('网络错误，稍后重试'));
            }
        });
    }

    // 拉取资料数据
    const fetchProfileData = async () => {
        try {
            const resp = await fetch('/profile/data/', { cache: 'no-store' });
            const json = await resp.json();
            if (resp.ok && json.status === 'success') {
                updateProfileUI(json.data);
            }
        } catch (err) {
            console.warn('获取资料失败');
        }
    };

    // 头像上传（使用 #avatar-icon 预览与隐藏文件输入）
    let avatarInput = document.getElementById('avatar-input');
    const avatarPreview = document.querySelector('.avatar-preview');
    const iconElAvatar = document.getElementById('avatar-icon');
    const saveAvatarBtn = document.querySelector('.save-avatar-btn');

    // 动态创建隐藏文件输入并绑定点击头像触发
    if (avatarPreview && !avatarInput) {
        avatarInput = document.createElement('input');
        avatarInput.type = 'file';
        avatarInput.id = 'avatar-input';
        avatarInput.accept = 'image/*';
        avatarInput.classList.add('hidden');
        const avatarSection = document.querySelector('.avatar-section');
        if (avatarSection) { avatarSection.appendChild(avatarInput); }
        avatarPreview.addEventListener('click', () => avatarInput.click());
    }

    if (avatarInput && iconElAvatar && saveAvatarBtn) {
        avatarInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;
            const reader = new FileReader();
            reader.onload = function(ev) {
                iconElAvatar.style.backgroundImage = `url('${ev.target.result}')`;
                saveAvatarBtn.disabled = false;
            };
            reader.readAsDataURL(file);
        });

        saveAvatarBtn.addEventListener('click', async () => {
            const file = avatarInput.files[0];
            if (!file) { alert('请选择图片'); return; }
            const formData = new FormData();
            formData.append('avatar', file);
            try {
                const resp = await fetch('/profile/avatar/upload/', {
                    method: 'POST',
                    headers: { 'X-CSRFToken': csrftoken },
                    body: formData
                });
                const json = await resp.json();
                if (resp.ok && json.status === 'success') {
                    alert('头像上传成功');
                    saveAvatarBtn.disabled = true;
                } else {
                    alert(json.message || '上传失败');
                }
            } catch (e) {
                alert('网络错误，稍后重试');
            }
        });
    }

    // 密码修改
    const currentPwdEl = document.getElementById('current-password');
    const newPwdEl = document.getElementById('new-password');
    const confirmPwdEl = document.getElementById('confirm-password');
    const savePwdBtn = document.getElementById('save-password-btn');
    const feedbackEl = document.getElementById('password-feedback');

    const setPwdFeedback = (msg, type='info') => {
        if (!feedbackEl) { alert(msg); return; }
        feedbackEl.textContent = msg || '';
        feedbackEl.classList.remove('error', 'success', 'info');
        feedbackEl.classList.add('form-feedback');
        feedbackEl.classList.add(type);
    };

    savePwdBtn?.addEventListener('click', async () => {
        const currentPwd = currentPwdEl?.value || '';
        const newPwd = newPwdEl?.value || '';
        const confirmPwd = confirmPwdEl?.value || '';
        if (!currentPwd || !newPwd || !confirmPwd) { setPwdFeedback('请完整填写当前密码与新密码', 'error'); return; }
        if (newPwd !== confirmPwd) { setPwdFeedback('两次输入的新密码不一致', 'error'); return; }
        savePwdBtn.disabled = true;
        savePwdBtn.textContent = '保存中...';
        try {
            const resp = await fetch('/profile/password/change/', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken },
                body: JSON.stringify({ current_password: currentPwd, new_password: newPwd, confirm_password: confirmPwd })
            });
            const json = await resp.json();
            if (resp.ok && json.status === 'success') {
                setPwdFeedback('密码修改成功', 'success');
                document.getElementById('current-password').value = '';
                document.getElementById('new-password').value = '';
                document.getElementById('confirm-password').value = '';
            } else {
                setPwdFeedback(json.message || '密码修改失败', 'error');
            }
        } catch (err) {
            setPwdFeedback('网络错误，稍后重试', 'error');
        } finally {
            savePwdBtn.disabled = false;
            savePwdBtn.textContent = '保存修改';
        }
    });

    // 初始数据加载与轮询
    fetchProfileData();
    this.profilePollingInterval = setInterval(fetchProfileData, 3000);
};

CloudPlatformApp.prototype.stopProfilePolling = function() {
    if (this.profilePollingInterval) {
        clearInterval(this.profilePollingInterval);
        this.profilePollingInterval = null;
    }
};

CloudPlatformApp.prototype.canManageUsers = function() {
    const role = (document.body.dataset.role || '').trim();
    const isStaffRaw = (document.body.dataset.isStaff || '').toLowerCase();
    const isStaff = (isStaffRaw === 'true' || isStaffRaw === '1');
    return isStaff || role === 'super_admin' || role === 'admin';
};

// ===== 用户管理页初始化逻辑 =====
CloudPlatformApp.prototype.initUsersPage = function() {
    // CSRF
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');

    // 元素引用
    const searchInput = document.getElementById('users-search-input');
    const roleFilter = document.getElementById('users-role-filter');
    const addBtn = document.getElementById('users-add-btn');
    const tbody = document.getElementById('users-table-body');
    const prevBtn = document.getElementById('users-prev-page');
    const nextBtn = document.getElementById('users-next-page');
    const pageInfo = document.getElementById('users-page-info');

    // 模态框元素
    const modal = document.getElementById('user-modal');
    const modalTitle = document.getElementById('user-modal-title');
    const modalClose = document.getElementById('user-modal-close');
    const modalCancel = document.getElementById('user-modal-cancel');
    const modalSave = document.getElementById('user-modal-save');
    const formUsername = document.getElementById('form-username');
    const formRole = document.getElementById('form-role');
    const formEmail = document.getElementById('form-email');
    const formPhone = document.getElementById('form-phone');
    const formActive = document.getElementById('form-active');
    const formPassword = document.getElementById('form-password');
    const formFeedback = document.getElementById('form-feedback');

    let state = { page: 1, pageSize: 10, hasNext: false, q: '', role: '' };
    let editUserId = null;

    const openModal = (mode='create', user=null) => {
        modal.classList.remove('hidden');
        formFeedback.textContent = '';
        if (mode === 'create') {
            modalTitle.textContent = '添加用户';
            editUserId = null;
            formUsername.value = '';
            formRole.value = 'user';
            formEmail.value = '';
            formPhone.value = '';
            formActive.value = 'true';
            formPassword.value = '';
            formPassword.disabled = false;
        } else {
            modalTitle.textContent = '编辑用户';
            editUserId = user?.id || null;
            formUsername.value = user?.username || '';
            formRole.value = user?.role || 'user';
            formEmail.value = user?.email || '';
            formPhone.value = user?.phone || '';
            formActive.value = user?.is_active ? 'true' : 'false';
            formPassword.value = '';
            formPassword.disabled = false; // 可选修改密码
        }
    };
    const closeModal = () => { modal.classList.add('hidden'); };

    // 拉取用户列表
    const fetchUsers = async () => {
        const params = new URLSearchParams({ q: state.q || '', page: state.page, page_size: state.pageSize });
        if (state.role) { params.append('role', state.role); }
        try {
            const resp = await fetch(`/users/manage/list/?${params.toString()}`, { cache: 'no-store' });
            const json = await resp.json();
            if (resp.ok && json.status === 'success') {
                const users = json.data.users || [];
                const pg = json.data.pagination || {};
                state.hasNext = !!pg.has_next;
                renderTable(users);
                pageInfo.textContent = `第 ${pg.page || state.page} 页 / 每页 ${pg.page_size || state.pageSize} 条，合计 ${pg.total || users.length}`;
                prevBtn.disabled = (state.page <= 1);
                nextBtn.disabled = !state.hasNext;
            } else {
                tbody.innerHTML = `<tr><td colspan="8" class="table-empty">${json.message || '加载失败'}</td></tr>`;
            }
        } catch (e) {
            tbody.innerHTML = `<tr><td colspan="8" class="table-empty">网络错误，稍后重试</td></tr>`;
        }
    };

    const renderTable = (users) => {
        if (!users.length) {
            tbody.innerHTML = `<tr><td colspan="8" class="table-empty">暂无数据</td></tr>`;
            return;
        }
        const currentRole = (document.body.dataset.role || '').trim();
        const isSuperAdmin = currentRole === 'super_admin';
        tbody.innerHTML = users.map(u => {
            const disableRow = (!isSuperAdmin && u.role === 'super_admin');
            const deleteBtnHtml = disableRow ? '' : `<button class="btn btn-danger btn-delete" ${disableRow ? 'disabled' : ''}>删除</button>`;
            return `
            <tr data-id="${u.id}" data-username="${u.username}" data-email="${u.email}" data-phone="${u.phone}" data-role="${u.role}" data-active="${u.is_active}">
                <td>${u.id}</td>
                <td>
                    <span>${u.username}</span>
                </td>
                <td>${roleText(u.role)}</td>
                <td>${u.email || ''}</td>
                <td>${u.phone || ''}</td>
                <td>
                    <label class="toggle-switch ${disableRow ? 'disabled' : ''}" title="${disableRow ? '无权限修改超级管理员' : '启用/禁用'}">
                        <input type="checkbox" class="user-active-toggle" ${u.is_active ? 'checked' : ''} ${disableRow ? 'disabled' : ''} aria-label="启用状态">
                        <span class="toggle-slider"></span>
                    </label>
                </td>
                <td>${u.date_joined}</td>
                <td>
                    <button class="btn btn-outline btn-edit" ${disableRow ? 'disabled' : ''}>编辑</button>
                    ${deleteBtnHtml}
                </td>
            </tr>
            `;
        }).join('');
    };

    const roleText = (role) => {
        switch (role) {
            case 'super_admin': return '超级管理员';
            case 'admin': return '管理员';
            default: return '普通用户';
        }
    };

    // 事件绑定
    searchInput?.addEventListener('input', CloudPlatform.debounce(() => {
        state.q = (searchInput.value || '').trim();
        state.page = 1;
        fetchUsers();
    }, 300));

    roleFilter?.addEventListener('change', () => {
        state.role = roleFilter.value || '';
        state.page = 1;
        fetchUsers();
    });

    addBtn?.addEventListener('click', () => openModal('create'));
    modalClose?.addEventListener('click', closeModal);
    modalCancel?.addEventListener('click', closeModal);

    // 保存（创建/编辑）
    modalSave?.addEventListener('click', async () => {
        formFeedback.textContent = '';
        const payload = {
            username: (formUsername.value || '').trim(),
            role: (formRole.value || 'user'),
            email: (formEmail.value || '').trim(),
            phone: (formPhone.value || '').trim(),
        };
        // 启用/禁用
        const activeVal = formActive.value;
        if (activeVal === 'true' || activeVal === 'false') payload.is_active = (activeVal === 'true');
        // 创建时可设置密码
        if (!editUserId) { payload.password = (formPassword.value || '').trim(); }
        if (!payload.username) { formFeedback.textContent = '用户名不能为空'; return; }
        if (payload.phone && (!/^\d{11}$/.test(payload.phone))) { formFeedback.textContent = '手机号格式不正确'; return; }
        try {
            const url = editUserId ? `/users/manage/update/${editUserId}/` : '/users/manage/create/';
            const resp = await fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken },
                body: JSON.stringify(payload)
            });
            const json = await resp.json();
            if (resp.ok && json.status === 'success') {
                CloudPlatform.showMessage(editUserId ? '编辑成功' : '新增成功', 'success');
                closeModal();
                fetchUsers();
            } else {
                formFeedback.textContent = json.message || '保存失败';
            }
        } catch (e) {
            formFeedback.textContent = '网络错误，稍后重试';
        }
    });

    // 表格操作（委托）
    tbody?.addEventListener('click', async (e) => {
        const target = e.target;
        const tr = target.closest('tr');
        if (!tr) return;
        const id = parseInt(tr.getAttribute('data-id'), 10);
        if (target.classList.contains('btn-edit')) {
            const user = {
                id,
                username: tr.getAttribute('data-username'),
                role: tr.getAttribute('data-role'),
                email: tr.getAttribute('data-email'),
                phone: tr.getAttribute('data-phone'),
                is_active: tr.getAttribute('data-active') === 'true'
            };
            const currentRole = (document.body.dataset.role || '').trim();
            if (currentRole === 'admin' && user.role === 'super_admin') {
                alert('无权限操作超级管理员');
                return;
            }
            openModal('edit', user);
        } else if (target.classList.contains('btn-delete')) {
            const rowRole = tr.getAttribute('data-role');
            const currentRole = (document.body.dataset.role || '').trim();
            if (currentRole === 'admin' && rowRole === 'super_admin') {
                alert('无权限删除超级管理员');
                return;
            }
            if (!confirm('确认删除该用户？')) return;
            try {
                const resp = await fetch(`/users/manage/delete/${id}/`, { method: 'POST', headers: { 'X-CSRFToken': csrftoken } });
                const json = await resp.json();
                if (resp.ok && json.status === 'success') {
                    CloudPlatform.showMessage('删除成功', 'success');
                    fetchUsers();
                } else {
                    alert(json.message || '删除失败');
                }
            } catch (e) {
                alert('网络错误，稍后重试');
            }
        }
    });

    // 状态开关切换（委托）
    tbody?.addEventListener('change', async (e) => {
        const input = e.target;
        if (!input.classList || !input.classList.contains('user-active-toggle')) return;
        const tr = input.closest('tr');
        if (!tr) return;
        const id = parseInt(tr.getAttribute('data-id'), 10);
        const newVal = !!input.checked;
        // 前端权限控制：管理员不可更改超级管理员
        const currentRole = (document.body.dataset.role || '').trim();
        const rowRole = tr.getAttribute('data-role');
        if (currentRole === 'admin' && rowRole === 'super_admin') {
            input.checked = tr.getAttribute('data-active') === 'true';
            CloudPlatform.showMessage('无权限修改超级管理员', 'error');
            return;
        }
        input.disabled = true;
        try {
            const resp = await fetch(`/users/manage/update/${id}/`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken },
                body: JSON.stringify({ is_active: newVal })
            });
            const json = await resp.json();
            if (resp.ok && json.status === 'success') {
                tr.setAttribute('data-active', newVal ? 'true' : 'false');
                CloudPlatform.showMessage(newVal ? '已启用' : '已禁用', 'success');
            } else {
                input.checked = !newVal;
                CloudPlatform.showMessage(json.message || '更新失败', 'error');
            }
        } catch (err) {
            input.checked = !newVal;
            CloudPlatform.showMessage('网络错误，稍后重试', 'error');
        } finally {
            input.disabled = false;
        }
    });

    // 翻页
    prevBtn?.addEventListener('click', () => { if (state.page > 1) { state.page -= 1; fetchUsers(); } });
    nextBtn?.addEventListener('click', () => { if (state.hasNext) { state.page += 1; fetchUsers(); } });

    // 初始加载
    fetchUsers();
};